package com.nginx.web.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.nginx.web.util.Result;
import com.nginx.web.util.ResultEnum;
import com.nginx.web.util.ReturnException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;

/**
 * 全局异常处理器
 *
 * @author liyuchen
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public Result notLoginException(NotLoginException e, HttpServletRequest request) {
        String requesturi = request.getRequestURI();
        log.error("请求地址'{}',登录失败'{}'", requesturi, e.getMessage());
        return Result.doBack(ResultEnum.TOKEN_PAST).setMsg(e.getMessage()).build();
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(NotRoleException.class)
    public Result noPermissionException(NotRoleException e, HttpServletRequest request) {
        String requesturi = request.getRequestURI();
        log.error("请求地址'{}',权限认证失败'{}'", requesturi, e.getMessage());
        return Result.error(e.getMessage());
    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requesturi = request.getRequestURI();
        String param = (String) request.getAttribute("body");
        log.error("请求地址'{}',发生系统异常.", requesturi, "【参数】" + param + " " + e.getCause());
        e.printStackTrace();
        Result error = Result.error();
        error.setResult(e.toString());
        return error;
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request) {
        String requesturi = request.getRequestURI();
        String param = (String) request.getAttribute("body");
        log.error("请求地址'{}',发生系统异常.", requesturi, "【参数】" + param + " " + e);
        e.printStackTrace();
        return Result.error(e.getMessage());
    }

    /**
     * 接口返回
     */
    @ExceptionHandler(ReturnException.class)
    public Result returnException(ReturnException e,HttpServletRequest request) {
        Result result = e.getResult();
        return result;
    }

}
